jQuery.validator.addMethod(
		"evenNumber", 
		function(value) { 
			return parseInt(value) % 2 == 0;
		}, 
		"Enter an even number!"
);

var currentlyPlaying = false;
var endOfGame = false;
var currentSelectedTile;

$(document).ready(function() {
	
	$('#dataHolder').data('actionCounter', -1);
	$('#dataHolder').data('previousPublicMessageTime', -1);
	$('#dataHolder').data('previousPrivateMessageTime', -1);
	
	var tiles = $(".tile");
	currentSelectedTile = $("#currentTile");
	
	tiles.hover ( 
		function() {
			currentSelectedTile[0].innerHTML = this.id;
		}, function() {
			currentSelectedTile[0].innerHTML = "";
		}
	);
	
	$("#postWrapper").hover(
		function() {
			$(this).attr('src', 'img/posthover.png');
		}, function() {
			$(this).attr('src', 'img/post.png');
		}
	);
	
	var playerTiles = $(".playerTile");
	playerTiles.hover (
		function() {
			$("#" + this.innerHTML).css("background-color", "#e13");
		}, function() {
			$("#" + this.innerHTML).css("background-color", "");
		}
	);
	
	$("#chatForm").validate({
		submitHandler: function(form) {
			$.post("GetGame",
				facebookURL({
					type: "postChatMessage",
					playerIndex: $.cookie('playerIndex'),
					chatMessage: escape($('#chatMessageInput').val())
				}));
			$('#chatMessageInput').val('');
		},
		rules: {
			chatMessageInput: {
				required: true,
				minlength: 1
			}
		},
		messages: {
			chatMessageInput: {
				required: "",
				minlength: ""
			}
		}
	});
		
	$('#soldCompanyForm input').keypress(function(e) {
		if (e.which == 13) {
			$('#soldCompanyForm').submit();
			return false;
		}
	});
	
	$('#chatForm input').keypress(function(e) {
		if (e.which == 13) {
			$('#chatForm').submit();
			return false;
		}
	});
	
});

function loadInfoCard() {
	if ($("#infoCard").has('table').size() == 0) {
		$("#infoCard").load("infoCard.html", function() {
			$("#infoCard").modal();
		});
	} else {
		$("#infoCard").modal();
	}
}

function loadCredits() {
	if ($("#credits").has('table').size() == 0) {
		$("#credits").load("credits.html", function() {
			$("#credits").modal();
		});
	} else {
		$("#credits").modal();
	}
}

function loadHelp() {
	
	var folding = function() { 
		$('.helpPart h3').click(function() {
			var clicked = $(this).siblings()[0];
			$('.helpPart div').filter(
				function() { return this !== clicked; }
			).hide("slow");
			$(this).siblings().toggle("slow");
		});
	};
	
	if ($("#userHelp").children().size() == 0) {
		$("#userHelp").load("help.html", function() {
			$("#userHelp").modal();
			folding();
		});
	} else {
		$("#userHelp").modal();
		folding();
	}
}

function loadVideo(movie) {
	
	var onClickEvent = '$.modal.close()';
	
	var closeButton = '<a id="videoCloseButton" href="#" onclick="' + onClickEvent + '">Close</a><br />'; 
	
	var movieEmbed = '<object width="640" height="385">' +
			'<param name="movie" value="http://www.youtube.com/v/' + movie + '&hl=en_US&fs=1&rel=0"></param>' +
			'<param name="allowFullScreen" value="true"></param>' + 
			'<param name="allowscriptaccess" value="always"></param>' + 
			'<embed' +
				' src="http://www.youtube.com/v/' + movie + '&hl=en_US&fs=1&rel=0"' +  
				' type="application/x-shockwave-flash"' +
					' allowscriptaccess="always"' +  
						' allowfullscreen="true"' +
							' width="640" height="385">' + 
			'</embed>' +
		'</object>';
	
	$("#video").html(closeButton + movieEmbed);
	$("#video").modal();
}

function repeatedActions() {
	getPrivateGameLog();
	getGameLog();
	getChatMessages();
	if (!currentlyPlaying) {
		getActionCounter();
	}
	setTimeout(repeatedActions, 500);
}
repeatedActions();

function getPlayerTile(data, ref) {
	var first = ref.substring(34);
	var x = first.charAt(0) == '/' ? 1 : parseInt(first.charAt(1));
	var second = first.substring(first.indexOf("e")+1);
	var y;
	
	if (second.length == 0) {
		y = 1;
	} else if (second.length == 3) {
		y = parseInt(second.charAt(1));
	} else { // second.length == 4 (to digits)
		y = parseInt(second.substring(1,3));
	}
	
	var newX = $(data).find('board').find('Tile-array')[x-1];
	var coor = $($(newX).find('Tile')[y-1]).find('coordinate');
	
	x = parseInt($(coor).find("x").text());
	y = parseInt($(coor).find("y").text())+1;
	x = String.fromCharCode(x+65);
	
	return ( x + y );
}

function parseReference(element) {
	var ref = element.attr('reference');
	if (ref === undefined) {
		return element;
	}
	
	var parts = ref.split("/");
	var current = element;
	for (var i = 0; i < parts.length; i++) {
		if (parts[i] == '..') {
			current = current.parent();
		} else {
			var currentPair = parseSubReference(parts[i]);
			var parentNode = $.browser.msie ? current[0].baseName : current[0].localName;
			current = $(current.parent().find(parentNode + " > " + currentPair[0])[currentPair[1]]);
		}
	}
	return current;
}

function parseSubReference(subref) { // strings that look like "someClass[5]" (only 1-9)
	var edgeLocation = subref.indexOf('[');
	if (edgeLocation == -1) {
		return [subref, 0];
	}
	var number = parseInt(subref.substring(edgeLocation+1, edgeLocation+2));
	return [subref.substring(0,edgeLocation), number - 1];
}

function updateGameData(data) {
	if ($(data).find('status').text() == 'pending') {
		return;
	}
	
	var currentState = $(data).find('state').text();
	
	// paint updated information
	$(data).find('board').find("Tile").filter(function() { 
	return $(this).find("onBoard").text() == 'true'; }).each(function () {
		var x = parseInt($(this).find("x").text());
		var y = parseInt($(this).find("y").text())+1;
		x = String.fromCharCode(x+65);
		
		var imageFilename;
		
		if (($(this).find("company").size()) == 0) {
			if (currentState != "GAME_ENDED" && 
					$(this).find('isBetweenSafeCompanies').text() == "true") {
				imageFilename = "betweensafe";
			} else {
				imageFilename = "nocompanytile";
			}
		} else {
			imageFilename = $(this).find("company").text().toLowerCase();
		}
		
		var imageFilenamePath = "img/" + imageFilename + ".png";
		$("#"+x+y).html("<img src='" + imageFilenamePath + "' />");
	});
	
	// things to do only once!
	if ($('.playerName').size() == 0) {
		
		// this is annoying and happens at unexpected times
//		try {
//			niftyplayer('soundPlayer').loadAndPlay('mp3/companySell.mp3');
//		} catch(err) {}
		
		
		$(data).find('players').children().each(function() {
			var currentIteratorPlayerID = $(this).find('userID').text();
			var currentIteratorPlayerName = $(this).find('name').text();
			
			var profilePicURL = "http://graph.facebook.com/" + currentIteratorPlayerID +"/picture";
			var img = new Image();
			$(img).attr('src', profilePicURL);
			$(img).attr('title', currentIteratorPlayerName);
			
			$("#playerList").append(
				"<span id='user" + currentIteratorPlayerID + "' class='playerName'></span>"	
			);
			$("#user" + currentIteratorPlayerID).append(img);
			
			$(".playerName img[title]").tooltip({ effect: 'fade'});
		});
	}
	
	$('.playerName').removeClass('playingUser');
	$(data).find('players').children().each(function() {
		var currentPlayerUserID = $(data).find('currentPlayerUserID').text();
		var currentIteratorPlayerID = $(this).find('userID').text();
		var nowPlayingClass = currentPlayerUserID == currentIteratorPlayerID;
		if (nowPlayingClass) {
			$("#user" + currentIteratorPlayerID).addClass('playingUser');
		}
	});
	
	
	var playerInfo = $(data).find('players').find('Player').filter(function() {
	return $(this).find('userID').text() == $.cookie('userID');	});
	
	$('#playerMoney').text("$" + playerInfo.find('cash').text());
	
	var counter = 0;
	playerInfo.find('Tile').each(function() {
		var attr = $(this).attr('reference');
		var currentTile = getPlayerTile(data, attr);
		$($('.playerTile')[counter]).text(currentTile);
		counter += 1;
	});
	
	counter = 0;
	playerInfo.find('stocks').find('int').each(function() {
		$($('.playerStock')[counter]).find('div').text($(this).text());
		counter += 1;
	});
	
	// Mangage current state
	if (currentState == "GAME_ENDED") {
		manageGameEnding(data);
		return;
	}
	
	if (currentState == "SELL_COMPANY_TO_COMPANY_GET_ORDER") {

		var currentSellOrderPlayer = $(data).find('SellOrder__playerIndexUserID').text();
		if (currentSellOrderPlayer != $.cookie('userID')) {
			$('#notInTurn').removeClass('hidden');
			return;
		}
		
		$('#notInTurn').addClass('hidden');
		currentlyPlaying = true;
		manangeSellCompanyToCompany(data);
		return;
	}
	
	var currentPlayer = $(data).find('currentPlayerUserID').text();
	if (currentPlayer != $.cookie('userID')) {
		$('#notInTurn').removeClass('hidden');
		return;
	}

	$('#notInTurn').addClass('hidden');
	currentlyPlaying = true;
	if (currentState == "MANAGE_PLACE_TILE_PRINT_DIALOG") {
		managePickTile();
	} else if (currentState == "MANAGE_BUY_STOCKS_PRINT_DIALOG") {
		pickBuyingStockAmount(data);
	} else if (currentState == "MANAGE_COMPANY_SELL_SAME_SIZED_DIALOG") {
		manageSellSameSize(data);
	} else if (currentState == "START_GAME_PRINT_CHOOSE_COMPANY_DIALOG") {
		manageStartCompany(data);
	} 
}

function manangeSellCompanyToCompany(data) {
	var soldCompany = $(data).find('SellOrder__soldCompanyEnum').text().toLowerCase();
	var soldCompanyUpper = soldCompany.substring(0,1).toUpperCase() + soldCompany.substring(1);
	var numberOfPlayerStocks = parseInt($("#" + soldCompany.toLowerCase() + "Stocks").text());
	
	if (numberOfPlayerStocks > 0) {
		$("#" + soldCompanyUpper).removeClass('limited');
		$("#soldCompanyOptions").removeClass('hidden');
		try {
			niftyplayer('soundPlayer').loadAndPlay('mp3/playerTurnSell.mp3');
		} catch(err) {}
	}

	$('#dataHolder').data('soldCompany', soldCompanyUpper);
	$("#soldCompanyForm").validate({
		submitHandler: function(form) {
			var soldCompany = $("#dataHolder").data('soldCompany');
			var numberOfPlayerStocks = parseInt($("#" + soldCompany.toLowerCase() + "Stocks").text());
			var stockSum = parseInt($(form).find("#toSell").val()) + 
							parseInt($(form).find("#toConvert").val());
			if (stockSum > numberOfPlayerStocks) {
				jAlert("You do not have enough stocks to go around", "Info");
			} else {
				$.post("GetGame", 
					facebookURL({
						type: "postGameData",
						Sell: $(form).find("#toSell").val(),
						Convert: $(form).find("#toConvert").val()
					}),
					function(newData) {
						currentlyPlaying = false;
						$("#toSell").val('');
						$("#toConvert").val('');
						$("#soldCompanyOptions").addClass('hidden');
						$("#" + $("#dataHolder").data('soldCompany')).addClass('limited');
					}
				);
			}
		},
		rules: {
			toSell: {
				required: true,
				range: [0,25]
			},
			toConvert: {
				required: true,
				range: [0,25],
				evenNumber: true
			}
		},
		messages: {
			toSell: {
				required: "Please enter a number",
				range: "Enter a smaller number"
			},
			toConvert: {
				required: "Enter an even number!",
				range: "Enter a smaller number",
				evenNumber: "Enter an even number!"
			}
		}
	});
	
	if (numberOfPlayerStocks == 0) {
		$("#toSell").val('0');
		$("#toConvert").val('0');
		$("#soldCompanyForm").submit();
	}
}

function managePickTile() {
	
	try {
		niftyplayer('soundPlayer').loadAndPlay('mp3/playerTurn.mp3');
	} catch(err) {}
	
	$("#pickTileOption").removeClass('hidden');
	$(".playerTile").click(function() {
		
		try {
			niftyplayer('soundPlayer').loadAndPlay('mp3/placeTile.mp3');
		} catch(err) {}
		
		var tile = $(this).text();
		$.post("GetGame",
			facebookURL({
				type: "postGameData",
				Tile: $(this).text(),
				Exit: "false"
			}),
			function(newData) {
				currentlyPlaying = false;
				$(".tile").css("background-color", "");
			});
		$(".tile").unbind('click');
		$(".playerTile").unbind('click');
		$(".tile").removeClass('currentPlayerTile');
		$("#pickTileOption").addClass('hidden');
		
	});
	
	$(".tile").filter(function() {
		var currentTile = this.id;
		return $(".playerTile").filter( 
				function(index) {
					return $(this).text() == currentTile;
				}
			).size() == 1;
	}).click(function() {
		try {
			niftyplayer('soundPlayer').loadAndPlay('mp3/placeTile.mp3');
		} catch(err) {}
		
		$.post("GetGame",
				facebookURL({
					type: "postGameData",
					Tile: this.id,
					Exit: "false"
				}),
				function(newData) {
					currentlyPlaying = false;
				});
			$(".tile").unbind('click');
			$(".playerTile").unbind('click');
			$(".tile").removeClass('currentPlayerTile');
			$("#pickTileOption").addClass('hidden');
	}).addClass('currentPlayerTile');
}

function manageSellSameSize(data) {
	$("#selectSoldCompany").removeClass('hidden');
	
	var manageCompanySellTimes = $(data).find('manageCompanySell__times').text();
	var manageCompanySameSized = manageCompanySellTimes == "1" ? 
			'manageCompanySell__SameSized1' : 'manageCompanySell__SameSized2';
	
	var sameSizeCompanies = parseReference($(data).find(manageCompanySameSized));
	var soldSelectAmount = sameSizeCompanies.children().size() - 1;
	$("#dataHolder").data('soldSelectAmount', soldSelectAmount);
	$("#dataHolder").data('currentSoldSelectAmount', 0);

	sameSizeCompanies.children().each(function() {
		var currentCompany = parseReference($(this)).find('name').text();
		$("#" + currentCompany).removeClass('limited');
		$("#" + currentCompany).click(function() {
			var previousAmount = $("#dataHolder").data('currentSoldSelectAmount');
			var currentAmount = previousAmount + 1;
			$("#dataHolder").data('currentSoldSelectAmount', currentAmount);
			$("#dataHolder").data(previousAmount.toString(), currentCompany);
			if (currentAmount == $("#dataHolder").data('soldSelectAmount')) {
				$.post("GetGame",
					facebookURL({	
						type: "postGameData",
						0: $("#dataHolder").data("0"),
						1: $("#dataHolder").data("1"),
						2: $("#dataHolder").data("2")
					}),
					function(newData) {
						currentlyPlaying = false;
						$("#dataHolder").data("0", "");
						$("#dataHolder").data("1", "");
						$("#dataHolder").data("2", "");
					}
				);
				$("#selectSoldCompany").addClass('hidden');
				$('.companySlot').unbind('click');
				$('.companySlot').addClass('limited');
			}
			$(this).unbind('click');
			$(this).addClass('limited');
		});
	});
}

function manageBuyStocks(data, amount) {
	$("#selectStocks").removeClass('hidden');
	$('.companySlot').find('div').text('0');
	$('#dataHolder').data('currentStockAmount', 0);
	var counter = 0;
	$(data).find('board').find('companies').children().each(function() {
		if ($(this).text() == 'true') {
			var currentCompany = $($('.companySlot')[counter]);
			currentCompany.removeClass('limited');
			currentCompany.click(function() {
				try {
					niftyplayer('soundPlayer').loadAndPlay('mp3/click.mp3');
				} catch(err) {}

				$('#dataHolder').data('currentStockAmount', $('#dataHolder').data('currentStockAmount')+1);
				var currentAmount = parseInt($(this).find('div').text());
				$(this).find('div').text((currentAmount+1).toString());
				if ($('#dataHolder').data('currentStockAmount') == amount) {
					$.post("GetGame", 
						facebookURL({
							type: "postGameData",
							Sackson: $("#sacksonSlot").text(),
							Zeta: $("#zetaSlot").text(),
							Hydra: $("#hydraSlot").text(),
							Fusion: $("#fusionSlot").text(),
							America: $("#americaSlot").text(),
							Phoenix: $("#phoenixSlot").text(),
							Quantum: $("#quantumSlot").text()
						}), 
						function(newData) {
							currentlyPlaying = false;
						}
					);
					$('.companySlot').unbind('click');
					$('.companySlot').find('div').text("");
					$('.companySlot').addClass('limited');
					$("#selectStocks").addClass('hidden');
				} 
			});
		}
		counter += 1;
	});
}

function pickBuyingStockAmount(data) {
	$("#selectStocksAmount").removeClass('hidden');
	$('.stockAmount').click(function() {
		try {
			niftyplayer('soundPlayer').loadAndPlay('mp3/click.mp3');
		} catch(err) {}
		$("#selectStocksAmount").addClass('hidden');
		$('.stockAmount').unbind('click');
		if ($(this).text() == '0') {
			$.post("GetGame", 
					facebookURL({
						type: "postGameData",
						Sackson: '0',
						Zeta: '0',
						Hydra: '0',
						Fusion: '0',
						America: '0',
						Phoenix: '0',
						Quantum: '0'
					}), 
					function(newData) {
						currentlyPlaying = false;
					}
				);
		}
		else {
			manageBuyStocks(data, parseInt($(this).text()));
		}
	});
}

function manageStartCompany(data) {
	$("#selectNewCompany").removeClass('hidden');
	var counter = 0;
	$(data).find('board').find('companies').children().each(function() {
		if ($(this).text() == 'false') {
			var currentCompany = $($('.companySlot')[counter]);
			currentCompany.removeClass('limited');
			currentCompany.click(function() {
				try {
					niftyplayer('soundPlayer').loadAndPlay('mp3/newCompany.mp3');
				} catch(err) {}
				$.post("GetGame",
					facebookURL({ 
						type: "postGameData",
						Company: this.id
					}),
					function(newData) {
						currentlyPlaying = false;
					}
				);
				$(".companySlot").unbind('click');
				$(".companySlot").addClass('limited');
				$("#selectNewCompany").addClass('hidden');
			});
		}
		counter += 1;
	});
}

function manageGameEnding(data) {
	try {
		niftyplayer('soundPlayer').loadAndPlay('mp3/endGame.mp3');
	} catch(err) {}
	
	$('#notInTurn').addClass('hidden');
	$("#endOfGame").removeClass('hidden');
	
	$("#newRankingWrapper").removeClass('hidden');
	$.get("GetUser",
			facebookURL({ type: "getUserDetails" }),
			function(userData) { $("#newRanking").text($(userData).find("rating").text()); }
		);

	var counter = 1;
	$("#scoreTable").html("<table><thead><tr><th></th><th>Username</th><th>Score</th></tr></thead>" +
			"<tbody id='scoreTableBody'></tbody></table>");
	var finalStandings = $(data).find('clientFinalStandings').children().each(function() {
		var currentPlayer = parseReference($(this));
		var newRow = "<tr><td>" + counter + "</td><td>" + currentPlayer.find('name').text() + "</td>" +
			"<td>$" + currentPlayer.find('cash').text() + "</td></tr>";
		$("#scoreTableBody").append(newRow);
		
//		if (counter == 1 && currentPlayer.find('userID').text() == $.cookie('userID')) {
//			$("#winnerStatusLink").removeClass('hidden');
//		}
		
		counter += 1;
	});
}

function manageEndGamePrematurely() {
	// remove handlers and similar
	$(".tile").unbind('click');
	$(".playerTile").unbind('click');
	$(".tile").removeClass('currentPlayerTile');
	$("#pickTileOption").addClass('hidden');
	
	$.post("GetGame",
			facebookURL({
				type: "postGameData",
				Tile: "Z9", // or some any other random string
				Exit: "true"
			}),
			function(newData) {
				currentlyPlaying = false;
			});
}


function scrollLog() {
	$('#playerLog').animate({
	    scrollTop: $('#playerLog').get(0).scrollHeight
	}, 1500);
}

function divToggle(object) {
			
}

